﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone.Tasks;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Resources;
using ExifLib;
using Coding4Fun.Toolkit.Controls;
using Microsoft.Phone.Shell;

namespace BigPicWatcher
{
    public partial class MainPage : PhoneApplicationPage
    {
        double _zoom;
        double Zoom
        {
            get { return _zoom; }
            set
            {
                X *= value / _zoom;
                Y *= value / _zoom;
                _zoom = value;
                TB_zoom.Text = (int)(_zoom * 100) + "%";
                pop_zoom.IsOpen = true;
                DrawSearchItems_Anim(g_zoom, 0.7, 0);
            }
        }
        public double X;//中心坐标
        public double Y;//中心坐标
        double svwidth = 480.0;
        double svheight = 730.0;
        public MainPage()
        {
            InitializeComponent();

            if (App.ScreenIsLock == true)
            {
                var btn_LockSrceen = ApplicationBar.MenuItems[2] as ApplicationBarMenuItem;
                btn_LockSrceen.Text = "解除屏幕锁定";
                BtnLock.Content = "解除屏幕锁定";
                if (App.pageorientation == PageOrientation.Portrait || App.pageorientation == PageOrientation.PortraitUp || App.pageorientation == PageOrientation.PortraitDown)
                {
                    this.SupportedOrientations = SupportedPageOrientation.Portrait;
                }
                else
                {
                    this.SupportedOrientations = SupportedPageOrientation.Landscape;
                }
            }
            
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.bitmap != null)
                showsuitpic();
            SetAppBarEnable(true);
        }
        void DrawPic()
        {
            if (App.bitmap == null) return;
            loadingScreen.Visibility = System.Windows.Visibility.Visible;
            foreach (var item in C_Pic.Children)
            {
                if (item is Image)
                    (item as Image).Source = null;
            }
            C_Pic.Children.Clear();
            Dispatcher.BeginInvoke(() =>
            {

                int JPGWidth = App.bitmap.PixelWidth;
                int JPGHeight = App.bitmap.PixelHeight;
                int showWidth = (int)(Zoom * JPGWidth);
                int showHeight = (int)(Zoom * JPGHeight);
                WriteableBitmap wbsourse = App.bitmap;
                C_Pic.Width = JPGWidth * Zoom;
                C_Pic.Height = JPGHeight * Zoom;

                int x = 0, y = 0;
                while (x < showWidth)
                {
                    int w = (showWidth - x) < 1000 ? (showWidth - x) : 1000;
                    while (y < showHeight)
                    {
                        int h = (showHeight - y) < 1000 ? (showHeight - y) : 1000;
                        Image img = new Image();
                        img.Source = GetOnePic(wbsourse, w, h, (x / Zoom), (y / Zoom));
                        Canvas.SetTop(img, y - y / 1000);
                        Canvas.SetLeft(img, x - x / 1000);
                        C_Pic.Children.Add(img);
                        y += h;
                    }
                    y = 0;
                    x += w;
                }

                this.translation.ScaleX = this.translation.ScaleY = initialScale = 1;
                loadingScreen.Visibility = System.Windows.Visibility.Collapsed;
            });
        }

        WriteableBitmap GetOnePic(WriteableBitmap picsourse, int weight, int height, double X, double Y)
        {
            WriteableBitmap picout = new WriteableBitmap(weight, height);
            for (int i = 0; i < picout.Pixels.Length; i++)
            {
                double x = ((i % picout.PixelWidth) / Zoom);
                double y = ((i / picout.PixelWidth) / Zoom);
                picout.Pixels[i] = picsourse.Pixels[(int)(Y + y) * picsourse.PixelWidth + (int)(X + x)];
            }
            return picout;
        }

        private void Click_OnCamera(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AblumList.xaml", UriKind.RelativeOrAbsolute));
        }
        double FitZoom, HeightFitZoom, WidthFitZoom;
        private void C_Pic_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (Zoom == FitZoom)
            {
                Zoom = 1;
            }
            else
            {
                Zoom = FitZoom;
            }
            DrawPic();
        }
        void showsuitpic()
        {
            Zoom = GetFitPicZoom();
            DrawPic();
        }
        double GetFitPicZoom()
        {
            double JPGWidth = App.bitmap.PixelWidth;
            double JPGHeight = App.bitmap.PixelHeight;
            HeightFitZoom = svheight / JPGHeight;
            WidthFitZoom = svwidth / JPGWidth;
            FitZoom = JPGWidth / JPGHeight > svwidth / svheight ? WidthFitZoom : HeightFitZoom;
            return FitZoom;
        }

        double initialScale;
        double centerX, centerY;
        private void GestureListener_PinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            initialScale = this.translation.ScaleX;
            pop_zoom.IsOpen = true;
            NeedToClose = false;
            TB_zoom.Text = (int)(_zoom * 100) + "%";
            DrawSearchItems_Anim(g_zoom, 0.7, 0.7);

            centerX = (sv_main.HorizontalOffset + App.bitmap.PixelWidth / 2) * Zoom;
            centerY = (sv_main.VerticalOffset + App.bitmap.PixelHeight / 2) * Zoom;
            translation.CenterX = centerX;
            translation.CenterY = centerY;
        }

        private void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
        {
            this.translation.ScaleX = this.translation.ScaleY = initialScale * e.DistanceRatio;
            TB_zoom.Text = (int)(_zoom * e.DistanceRatio * 100) + "%";
        }

        private void GestureListener_PinchCompleted(object sender, PinchGestureEventArgs e)
        {
            NeedToClose = true;
            Zoom = Zoom * e.DistanceRatio;
            DrawPic();
        }
        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            App.pageorientation = e.Orientation;
            if (App.pageorientation == PageOrientation.Portrait || App.pageorientation == PageOrientation.PortraitUp || App.pageorientation == PageOrientation.PortraitDown)
            {
                svwidth = 480.0;
                svheight = 730.0;
            }
            else
            {
                svwidth = 730.0;
                svheight = 480.0;
            }
            if (App.bitmap == null)
                return;
            GetFitPicZoom();
            DrawPic();
        }

        public void DrawSearchItems_Anim(UIElement uielement, double Start, double End, string attrname = "(Opacity)")
        {
            //实例化Storyboard
            Storyboard storyboard = new Storyboard();
            DoubleAnimation doubleAnimationX = new DoubleAnimation();
            doubleAnimationX.Duration = new Duration(TimeSpan.FromMilliseconds(2000));
            doubleAnimationX.EasingFunction = new SineEase();
            doubleAnimationX.From = Start;
            doubleAnimationX.To = End;
            Storyboard.SetTarget(doubleAnimationX, uielement);
            Storyboard.SetTargetProperty(doubleAnimationX, new PropertyPath(attrname));
            storyboard.Children.Add(doubleAnimationX);
            storyboard.Completed += new EventHandler(storyboard_Completed);
            storyboard.Begin();
        }
        bool NeedToClose = true;
        void storyboard_Completed(object sender, EventArgs e)
        {
            if (NeedToClose)
            pop_zoom.IsOpen = false;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            if (pop_zoomSet.IsOpen == true)
            {
                pop_zoomSet.IsOpen = false;
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/AblumList.xaml", UriKind.Relative));
            }
            base.OnBackKeyPress(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            for (int i = 0; i < C_Pic.Children.Count; i++)
            {
                (C_Pic.Children[i] as Image).Source = null;
                C_Pic.Children.RemoveAt(i--);
            }
            base.OnNavigatedFrom(e);
        }

        private void Click_ToMode1(object sender, EventArgs e)
        {
            App.ViewMode = 1;
            App.ToViewPage(this);
        }

        private void Click_SetZoom(object sender, EventArgs e)
        {
            OpenZoomSet();
            TbZoomSet.Focus();
        }

        private void Click_LockSrceen(object sender, EventArgs e)
        {
            LockSrceen();
        }

        void LockSrceen()
        {
            var btn_LockSrceen = ApplicationBar.MenuItems[2] as ApplicationBarMenuItem;
            if (!App.ScreenIsLock)
            {
                btn_LockSrceen.Text = "解除屏幕锁定";
                BtnLock.Content = "解除屏幕锁定";
                App.ScreenIsLock = true;
                if (App.pageorientation == PageOrientation.Portrait || App.pageorientation == PageOrientation.PortraitUp || App.pageorientation == PageOrientation.PortraitDown)
                {
                    this.SupportedOrientations = SupportedPageOrientation.Portrait;
                }
                else
                {
                    this.SupportedOrientations = SupportedPageOrientation.Landscape;
                }
            }
            else
            {
                btn_LockSrceen.Text = "锁定屏幕方向";
                BtnLock.Content = "锁定屏幕方向";
                App.ScreenIsLock = false;
                this.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
            }
        }

        private void GestureListener_Hold(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            OpenZoomSet();
        }

        void OpenZoomSet()
        {
            pop_zoomSet.IsOpen = true;
        }

        void BtnWidthFit_Click(object sender, RoutedEventArgs e)
        {
            Zoom = WidthFitZoom;
            DrawPic();
            pop_zoomSet.IsOpen = false;
        }
        void BtnHeightFit_Click(object sender, RoutedEventArgs e)
        {
            Zoom = HeightFitZoom;
            DrawPic();
            pop_zoomSet.IsOpen = false;
        }
        void BtnScreenFit_Click(object sender, RoutedEventArgs e)
        {
            Zoom = FitZoom;
            DrawPic();
            pop_zoomSet.IsOpen = false;
        }
        void BtnFull_Click(object sender, RoutedEventArgs e)
        {
            Zoom = 1;
            DrawPic();
            pop_zoomSet.IsOpen = false;
        }

        List<ApplicationBarIconButton> AppBtn;
        void ChangeAppBarToText()
        {
            AppBtn = new List<ApplicationBarIconButton>();
            foreach (var btn in ApplicationBar.Buttons)
            {
                AppBtn.Add(btn as ApplicationBarIconButton);
            }
            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton BtnOk = new ApplicationBarIconButton(new Uri("/Icons/appbar.check.rest.png", UriKind.Relative));
            BtnOk.Text = "确定";
            BtnOk.Click += BtnOk_Click;
            ApplicationBar.Buttons.Add(BtnOk);
            ApplicationBarIconButton BtnClose = new ApplicationBarIconButton(new Uri("/Icons/appbar.close.rest.png", UriKind.Relative));
            BtnClose.Text = "取消";
            BtnClose.Click += BtnClose_Click;
            ApplicationBar.Buttons.Add(BtnClose);
            ApplicationBar.IsMenuEnabled = false;
        }
        void ChangeAppBarToApp()
        {
            if (AppBtn != null)
            {
                ApplicationBar.Buttons.Clear();
                foreach (var btn in AppBtn)
                {
                    ApplicationBar.Buttons.Add(btn);
                }
                AppBtn = null;
            }
            ApplicationBar.IsMenuEnabled = true;
        }

        void BtnClose_Click(object sender, EventArgs e)
        {
            BtnFull.Focus();
        }

        void BtnOk_Click(object sender, EventArgs e)
        {
            string tmp = TbZoomSet.Text;
            try
            {
                Zoom = Convert.ToDouble(tmp) / 100;
                DrawPic();
                pop_zoomSet.IsOpen = false;
                TbZoomSet.Text = "";
            }
            catch
            {
                var messagePrompt = new MessagePrompt
                {
                    Title = "警告！",
                    Message = "请输入数字！"
                };
                messagePrompt.Show();
            }
        }

        private void TbZoomSet_GotFocus(object sender, RoutedEventArgs e)
        {
            ChangeAppBarToText();
        }

        private void TbZoomSet_LostFocus(object sender, RoutedEventArgs e)
        {
            ChangeAppBarToApp();
        }


        private void C_Pic_MouseEnter(object sender, MouseEventArgs e)
        {
            if (pop_zoomSet.IsOpen == true)
                pop_zoomSet.IsOpen = false;
        }

        private void BtnLock_Click(object sender, RoutedEventArgs e)
        {
            LockSrceen();
        }

        private void Click_About(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageAbout.xaml", UriKind.Relative));
        }

        private void Click_Next(object sender, EventArgs e)
        {
            loadingScreen.Visibility = System.Windows.Visibility.Visible;
            SetAppBarEnable(false);
            Dispatcher.BeginInvoke(() =>
            {
                if (App.ShowNextOrPrevious(this))
                {
                    showsuitpic();
                }
                loadingScreen.Visibility = System.Windows.Visibility.Collapsed;
                SetAppBarEnable(true);
            });
        }

        private void Click_Previous(object sender, EventArgs e)
        {
            loadingScreen.Visibility = System.Windows.Visibility.Visible;
            SetAppBarEnable(false);
            Dispatcher.BeginInvoke(() =>
            {
                if (App.ShowNextOrPrevious(this, -1))
                {
                    showsuitpic();
                }
                loadingScreen.Visibility = System.Windows.Visibility.Collapsed;
                SetAppBarEnable(true);
            });
        }
        void SetAppBarEnable(bool b)
        {
            this.ApplicationBar.IsMenuEnabled = b;
            (this.ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = App.PictureNum == 0 ? false : b;
            (this.ApplicationBar.Buttons[2] as ApplicationBarIconButton).IsEnabled = App.PictureNum == App.SelectedAlbum.Count - 1 ? false : b;
        }
    }
}